/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.amap.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.LngLonUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.amap.dto.AmapApiResponseDTO;
import org.jeecg.modules.third.amap.dto.GpsDTO;
import org.jeecg.modules.third.amap.dto.MapDirectionDTO;
import org.jeecg.modules.third.amap.dto.RegeoDTO;
import org.jeecg.modules.third.sendsms.util.HttpClientUtil;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 高德API
 *
 * @author duanlikao
 * @created 2021/4/17
 */
@Service
@Slf4j
public class AmapService {

    private static final String AMAP_GPS_API_KEY = "amap_gps_api_";

    private static final String AMAP_GPS_ORDER_KEY = "amap_gps_order_";

    public static final int AMAP_GPS_API_KEY_EXPIRE = 86400 * 7;

    private static final String BASE_PATH = "https://restapi.amap.com";

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 高德API 通过IP定位地址
     */
    public String ipConvertAddress(String IPAddress) {
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if (systemConfig == null || !systemConfig.getAmapIzUse()) {
            log.warn("高德地图API未开启");
            return StrUtil.EMPTY;
        }

        String url  = BASE_PATH + "/v3/ip?ip=" + IPAddress +  "&output=json&key="+ systemConfig.getAmapKey();
        log.info("通过IP定位地址请求 -> {}", url);
        String result = HttpClientUtil.doGet(url);
        JSONObject jsonobject = JSONObject.parseObject(result);
        log.info("通过IP定位地址回执 <- {}", jsonobject.toString());
        if (!"1".equals(jsonobject.getString("status"))) {
            return StrUtil.EMPTY;
        }

        return jsonobject.getString("province") + jsonobject.getString("city");
    }


    /**
     * 高德地图WebAPI : 地址转化为高德坐标
     * String address：高德地图地址
     * KEY-为地图key,这里的key要申请对应服务的key 一定要选择“web服务”项的key
     * 输入：成都市武侯区
     * 输出：104.043390,30.641982
     */
    public String coordinate(String address) {
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if (systemConfig == null || !systemConfig.getAmapIzUse()) {
            throw new JeecgBootException("高德地图查询服务暂未开启,请联系管理。");
        }

        try {
            address = URLEncoder.encode(address, "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.info("coordinate UnsupportedEncodingException :{}",e.getMessage());
        }
        String url = BASE_PATH + "/v3/geocode/geo?address=" + address + "&output=json&key="+ systemConfig.getAmapKey();
        log.info("通过地址转化为高德坐标请求 -> {}", url);
        String coordinateString = null;
        try {
            String temp = HttpClientUtil.doGet(url);
            log.info("通过地址转化为高德坐标回执 <- {}", temp);
            JSONObject jsonobject = JSONObject.parseObject(temp);
            JSONArray pathArray = jsonobject.getJSONArray("geocodes");
            coordinateString = pathArray.getJSONObject(0).getString("location");
        } catch (Exception e) {
            log.info("coordinate Exception :{}", e.getMessage());
        }

        return coordinateString;
    }


    /**
     * 逆地理编码  经纬度坐标解析地址
     * 传入内容规则：经度在前，纬度在后，经纬度间以“,”分割，经纬度小数点后不要超过 6 位。
     * @param longitude 经度
     * @param latitude 维度
     * @return
     */
    public RegeoDTO coordinateRegeo(String longitude, String latitude) {

        HyConfig systemConfig = HyConfigUtils.getConfig();
        if (systemConfig == null || !systemConfig.getAmapIzUse()) {
            throw new JeecgBootException("高德地图查询服务暂未开启,请联系管理。");
        }

        String coordinate = longitude + "," + latitude;
        String url = BASE_PATH + "/v3/geocode/regeo?location=" + coordinate + "&output=json&key="+ systemConfig.getAmapKey()
                + "&radius=1000&extensions=all";

        RegeoDTO regeoDTO = new RegeoDTO();
        try {
            String temp = HttpClientUtil.doGet(url);
            JSONObject jsonobject = JSONObject.parseObject(temp);

            //返回值为 0 或 1，0 表示请求失败；1 表示请求成功。
            if (!"1".equals(jsonobject.getString("status"))) {
                log.warn("逆地理编码接口错误, {}", jsonobject.getString("info"));
                return regeoDTO;
            }

            JSONObject regeocode = jsonobject.getJSONObject("regeocode");
            JSONObject addressComponent = regeocode.getJSONObject("addressComponent");

            regeoDTO.setProvince(addressComponent.getString("province"));
            regeoDTO.setCity(addressComponent.getString("city"));
            regeoDTO.setDistrict(addressComponent.getString("district"));
            //街道
            regeoDTO.setTownship(addressComponent.getString("township"));
            //县区编码
            regeoDTO.setAreaCode(addressComponent.getString("adcode"));
            //详细地址可以取组上层的formataddress，也可以在这里用省市县拼接，结果是一样的
            regeoDTO.setAddress(regeoDTO.getProvince() + regeoDTO.getCity() + regeoDTO.getDistrict() + regeoDTO.getTownship());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("逆地理编码异常, {}", e.getMessage());
        }

        return regeoDTO;
    }


    /**
     * 高德地图WebAPI : 驾车路径规划 计算两地之间行驶的距离(米)
     * String origins:起始坐标
     * String destination:终点坐标
     *输入：原坐标:{116.45925,39.910031}，目标坐标:{116.587922,40.081577}
     *输出：25424
     */
    public  String distance(String origins, String destination) {
        String distanceString = null;
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getAmapIzUse()){
            throw new JeecgBootException("高德地图查询服务暂未开启,请联系管理。");
        }
        try {
            String url = BASE_PATH + "/v3/distance?" + "origins=" + origins + "&destination=" + destination
                    + "&output=json"+ "&key="+ systemConfig.getAmapKey();
            String aa = HttpClientUtil.doGet(url);
            JSONObject jsonobject =JSONObject.parseObject(aa);
            JSONArray pathArray = jsonobject.getJSONArray("results");
            distanceString = pathArray.getJSONObject(0).getString("distance");
        } catch (Exception e) {
            log.info("distance Exception :{}", e.getMessage());
        }
        return distanceString;
    }

//    /**
//     * 货车路径规划
//     * String origins:起始坐标
//     * String destination:终点坐标
//     *输入：原坐标:{116.45925,39.910031}，目标坐标:{116.587922,40.081577}
//     * @return
//     */
//    private  List<GpsDTO>  direction(String origins, String destination) {
//        HyConfig systemConfig = HyConfigUtils.getConfig();
//        if(systemConfig == null || !systemConfig.getAmapIzUse()){
//            throw new JeecgBootException("高德地图查询服务暂未开启,请联系管理。");
//        }
//        List<GpsDTO> newMapGpsDTOs =  new ArrayList<>();
//        try {
//            String url = BASE_PATH + "/v4/direction/truck?size=4&" + "origin=" + origins + "&destination=" + destination
//                    + "&output=json"+ "&key="+ systemConfig.getAmapKey();
//            String aa = HttpClientUtil.doGet(url);
//            LOGGER.info("distance direction url :{} res :{}",url ,aa);
//            if(StringUtils.isNotEmpty(aa)){
//                newMapGpsDTOs =  getTrackTrajectory( aa);
//            }
//            return newMapGpsDTOs;
//        } catch (Exception e) {
//            LOGGER.info("distance direction Exception :{}",e.getMessage());
//        }
//        return newMapGpsDTOs;
//    }
//    /**
//     * 小客车路径规划
//     * String origins:起始坐标
//     * String destination:终点坐标
//     *输入：原坐标:{116.45925,39.910031}，目标坐标:{116.587922,40.081577}
//     * @return
//     */
//    private  List<GpsDTO>  directionDriving(String origins, String destination) {
//        HyConfig systemConfig = HyConfigUtils.getConfig();
//        if(systemConfig == null || !systemConfig.getAmapIzUse()){
//            throw new JeecgBootException("高德地图查询服务暂未开启,请联系管理。");
//        }
//        List<GpsDTO> newMapGpsDTOs =  new ArrayList<>();
//        try {
//
//            String url = BASE_PATH + "/v3/direction/driving?origin="  + origins + "&destination=" + destination
//                    + "&extensions=all&output=json"+ "&key="+ systemConfig.getAmapKey();;
//            String aa = HttpClientUtil.doGet(url);
//            LOGGER.info("distance directionDriving url :{} res :{}",url ,aa);
//            if(StringUtils.isNotEmpty(aa)){
//                newMapGpsDTOs =  getTrackTrajectory1( aa);
//            }
//
//            return newMapGpsDTOs;
//        } catch (Exception e) {
//            LOGGER.info("distance directionDriving Exception :{}",e.getMessage());
//        }
//        return newMapGpsDTOs;
//    }

    /**
     * 未来路径规划
     * 适用于查询未来7天的路径规划结果
     * @param origins
     * @param destination
     * cartype = 4 大车
     * strategy = 9.躲避拥堵和收费，不走高速
     * firsttime 出发时间，第一个时间戳 unix时间戳，精确到秒，必须是未来时间，如果小于当前时间会报错。
     * interval 时间间隔单位：秒
     * count 时间点个数最多支持48个
     *
     * @return
     */
    private MapDirectionDTO directionDriving(String origins, String destination) {
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if (systemConfig == null || !systemConfig.getAmapIzUse()) {
            throw new JeecgBootException("高德地图查询服务暂未开启,请联系管理。");
        }

        try {
            long firsttime = System.currentTimeMillis()/ 1000 ;
            firsttime = firsttime + 60*60*3;
            int interval = 5* 10;
            String url = BASE_PATH + "/v3/direction/driving?origin="  + origins + "&destination=" + destination
                   + "&strategy=9&cartype=0&count=1&interval=" + interval + "&firsttime=" + firsttime
                    +"&extensions=all&output=json"+ "&key="+ systemConfig.getAmapKey();
            String res = HttpClientUtil.doGet(url);
            log.info("高德地图模拟轨迹 -> {}", url);
            return getTrackTrajectory(res);
        } catch (Exception e) {
            log.error("高德地图模拟轨迹请求异常 {}", e.getMessage());
        }

        return null;
    }

    private MapDirectionDTO getTrackTrajectory(String TrackTrajectory) {
        List<GpsDTO> newMapGpsDTOs = new ArrayList<>();
        if (StrUtil.isEmpty(TrackTrajectory)) {
            return null;
        }

        MapDirectionDTO mapDirectionDTO = new MapDirectionDTO();
        AmapApiResponseDTO apiResponseDTO = JSONObject.parseObject(TrackTrajectory, AmapApiResponseDTO.class);
        if ("1".equals(apiResponseDTO.getStatus()) && "OK".equals(apiResponseDTO.getInfo()) &&
                "10000".equals(apiResponseDTO.getInfocode()) && apiResponseDTO.getRoute() != null ) {

            JSONObject jsonobject = JSONObject.parseObject(JSONObject.toJSONString(apiResponseDTO.getRoute()));
            JSONArray pathArray = jsonobject.getJSONArray("paths");
            JSONArray stepsPathArray = pathArray.getJSONObject(0).getJSONArray("steps");

            double totalDistance = 0d;
            List<GpsDTO> mapGpsDTOS = new ArrayList <>();
            for (int i = 0; i < stepsPathArray.size(); i++) {
                String polyline = stepsPathArray.getJSONObject(i).get("polyline").toString();
                if (StrUtil.isEmpty(polyline)) {
                    continue;
                }

                String[] sourceArray = polyline.split(";");
                for (int j = 0; j < sourceArray.length; j++) {
                    String[] lanLatString = sourceArray[j].split(",");
                    GpsDTO mapGpsDTO = new GpsDTO();
                    mapGpsDTO.setLon(lanLatString[0]);
                    mapGpsDTO.setLat(lanLatString[1]);
                    mapGpsDTOS.add(mapGpsDTO);
                }

                String distance = stepsPathArray.getJSONObject(i).get("distance").toString();
                if (StrUtil.isNotEmpty(distance)) {
                    totalDistance += Double.valueOf(distance);
                }
            }

            this.fromData(newMapGpsDTOs, mapGpsDTOS);
            //默认是米，除以1000转换为公里
            mapDirectionDTO.setDistance(String.valueOf(totalDistance / 1000));
            mapDirectionDTO.setGpsDTOList(newMapGpsDTOs);

        } else {
            throw new JeecgBootException("高德地图查询服务：" + apiResponseDTO.getInfocode() + apiResponseDTO.getInfo());
        }

        return mapDirectionDTO;
    }

//
//    private List<GpsDTO> getTrackTrajectory( String TrackTrajectory) {
//        List<GpsDTO> newMapGpsDTOs =  new ArrayList<>();
//        if(StringUtils.isBlank(TrackTrajectory)){
//            return newMapGpsDTOs;
//        }
//        AmapApiResponseDTO apiResponseDTO = JSONObject.parseObject(TrackTrajectory, AmapApiResponseDTO.class);
//        if(apiResponseDTO.getErrcode() ==0  &&
//                apiResponseDTO.getErrmsg().equals("OK") &&
//                apiResponseDTO.getData()!=null ){
//
//            JSONObject jsonobject =  JSONObject.parseObject(JSONObject.toJSONString(apiResponseDTO.getData()));
//           // JSONArray pathArray = jsonobject.getJSONObject("route").getJSONArray("paths"); //货车轨迹
//            JSONArray pathArray = jsonobject.getJSONArray("paths");
//            JSONArray stepsPathArray = pathArray.getJSONObject(0).getJSONArray("steps");
//            List<GpsDTO>  mapGpsDTOS = new ArrayList <>();
//            for(int i=0;i<stepsPathArray.size();i++) {
//               String polyline = stepsPathArray.getJSONObject(i).get("polyline").toString();
//               if(StringUtils.isEmpty(polyline)){
//                   continue;
//               }
//                String[] sourceArray = polyline.split(";");
//                for (int j = 0; j < sourceArray.length; j++) {
//                    String[] lanLatString = sourceArray[j].split(",");
//                    GpsDTO mapGpsDTO = new GpsDTO();
//                    mapGpsDTO.setLon(lanLatString[0]);
//                    mapGpsDTO.setLat(lanLatString[1]);
//                    mapGpsDTOS.add(mapGpsDTO);
//                }
//            }
//            this.fromData(newMapGpsDTOs, mapGpsDTOS);
//        }else{
//            throw new JeecgBootException("高德地图查询服务："+apiResponseDTO.getErrcode()+apiResponseDTO.getErrmsg());
//        }
//        return newMapGpsDTOs;
//    }

    /**
     * 数据整理
     * @param newMapGpsDTOs
     * @param mapGpsDTOS
     */
    private void fromData(List<GpsDTO> newMapGpsDTOs, List<GpsDTO> mapGpsDTOS) {
        int a = mapGpsDTOS.size();
        int b = 1;
        if (a > 1000 && a <= 2000) {
            b = 2;
        } else if (a > 2000 && a <= 3000) {
            b = 3;
        } else if (a > 3000 && a <= 4000) {
            b = 4;
        } else if (a > 4000 && a <= 5000) {
            b = 5;
        } else if (a > 5000 && a <= 6000) {
            b = 6;
        } else if (a > 6000 && a <= 7000) {
            b = 7;
        } else if (a > 7000 && a <= 8000) {
            b = 8;
        } else if (a > 8000 && a <= 9000) {
            b = 9;
        } else if (a > 9000) {
            b = 10;
        }

        int n = 1;
        for (GpsDTO mapGpsDTO : mapGpsDTOS) {
            if (n % b == 0) {
                newMapGpsDTOs.add(mapGpsDTO);
            }
            n++;
        }
    }

    /**
     * 获取运单的模拟轨迹
     * @param hyShippingNote
     * @return
     */
    public List<GpsDTO> getMapGps(HyShippingNote hyShippingNote)  {
        String  origins = null;
        String destination = null;
        if(hyShippingNote.getSendLongitude()==null || hyShippingNote.getSendLatitude()==null ||
                hyShippingNote.getSendLongitude().compareTo(BigDecimal.ZERO)==0 ||
                hyShippingNote.getSendLatitude().compareTo(BigDecimal.ZERO)==0 ){
            String sendresl  =  coordinate(hyShippingNote.getSendAddress());
            origins = StringUtils.isNotBlank(sendresl) ? sendresl : StringUtils.EMPTY;
        }else{
            double[] d = LngLonUtil.bd09_To_Gcj02(hyShippingNote.getSendLatitude().doubleValue(), hyShippingNote.getSendLongitude().doubleValue());
            origins = new BigDecimal(d[1]).setScale(5, RoundingMode.DOWN).toString() + "," + new BigDecimal(d[0]).setScale(5, RoundingMode.DOWN).toString();
            //origins = hyShippingNote.getSendLongitude().toString()+","+hyShippingNote.getSendLatitude().toString();
        }
        if( hyShippingNote.getReceiveLongitude()==null || hyShippingNote.getReceiveLatitude()==null ||
                hyShippingNote.getReceiveLongitude().compareTo(BigDecimal.ZERO)==0 ||
                hyShippingNote.getReceiveLatitude().compareTo(BigDecimal.ZERO)==0 ){
            String receiveresl  =  this.coordinate(hyShippingNote.getReceiveAddress());
            destination = StringUtils.isNotBlank(receiveresl) ? receiveresl : StringUtils.EMPTY;
        }else{
            double[] d = LngLonUtil.bd09_To_Gcj02(hyShippingNote.getReceiveLatitude().doubleValue(), hyShippingNote.getReceiveLongitude().doubleValue());
            destination = new BigDecimal(d[1]).setScale(5, RoundingMode.DOWN).toString() + "," + new BigDecimal(d[0]).setScale(5, RoundingMode.DOWN).toString();
            //destination = hyShippingNote.getReceiveLongitude().toString()+","+hyShippingNote.getReceiveLatitude().toString();
        }
        if(StringUtils.isBlank(origins) || StringUtils.isBlank(destination)  ){
            return new ArrayList <>();
        }
        Date statusDtLoading = hyShippingNote.getStatusDtLoading();
        Date statusDtUnloading = hyShippingNote.getStatusDtUnloading();

        int second = DateUtils.getDifferentDaysByMillisecond(statusDtLoading, statusDtUnloading);

        String key = AMAP_GPS_API_KEY+origins+"_"+destination;
        Object tokenObject = redisUtil.hasKey(key) && redisUtil.get(key) != null ? redisUtil.get(key) : null;
        List<GpsDTO>  mapGpsDTOS = tokenObject != null ?  JSONObject.parseArray(tokenObject.toString(),GpsDTO.class) : new ArrayList<>() ;
        if(CollectionUtils.isEmpty(mapGpsDTOS)){
            MapDirectionDTO mapDirectionDTO = this.directionDriving(origins, destination);
            if (CollUtil.isNotEmpty(mapDirectionDTO.getGpsDTOList())) {
                mapGpsDTOS = mapDirectionDTO.getGpsDTOList();
            } else {
                log.error("高德模拟轨迹返回数据为空, 运单号: {} - {} - {}", hyShippingNote.getShippingNoteNumber(), origins, destination);
            }

            if (CollUtil.isNotEmpty(mapGpsDTOS)){
                redisUtil.set(key, JSONObject.toJSONString(mapGpsDTOS), AMAP_GPS_API_KEY_EXPIRE);
            }
        }

        if(second > 0 && CollUtil.isNotEmpty(mapGpsDTOS)) {
            int abc = second / mapGpsDTOS.size();
            for (GpsDTO mapGpsDTO : mapGpsDTOS) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(statusDtLoading);
                cal.add(Calendar.SECOND, abc);//秒
                Date dates = cal.getTime();
                mapGpsDTO.setPositionTime(DateUtils.dateTimeToString(dates));
                statusDtLoading = dates;
            }
        }

        return mapGpsDTOS;
    }

    /**
     * 获取货源的模拟轨迹
     * @param order
     * @return
     */
    public MapDirectionDTO getMapGpsOrder(HyOrder order)  {
        String origins = null;
        String destination = null;
        if (order.getSendLongitude() == null
         || order.getSendLatitude() == null
         || order.getSendLongitude().compareTo(BigDecimal.ZERO) == 0
         || order.getSendLatitude().compareTo(BigDecimal.ZERO) == 0) {
            String sendresl = coordinate(order.getSendAddress());
            origins = StringUtils.isNotBlank(sendresl) ? sendresl : StringUtils.EMPTY;
        } else {
            origins = order.getSendLongitude().toString() + "," + order.getSendLatitude().toString();
        }

        if (order.getReceiveLongitude() == null
         || order.getReceiveLatitude() == null
         || order.getReceiveLongitude().compareTo(BigDecimal.ZERO) == 0
         || order.getReceiveLatitude().compareTo(BigDecimal.ZERO) == 0 ) {
            String receiveresl = this.coordinate(order.getReceiveAddress());
            destination = StringUtils.isNotBlank(receiveresl) ? receiveresl : StringUtils.EMPTY;
        } else {
            destination = order.getReceiveLongitude().toString() + "," + order.getReceiveLatitude().toString();
        }

        if (StringUtils.isBlank(origins) || StringUtils.isBlank(destination)) {
            return null;
        }
//        Date statusDtLoading = order.getStatusDtLoading();
//        Date statusDtUnloading = order.getStatusDtUnloading();
//        int second = DateUtils.getDifferentDaysByMillisecond(statusDtLoading, statusDtUnloading);

        String key = AMAP_GPS_ORDER_KEY + origins + "_" + destination;
        Object mapDirectionObject = redisUtil.hasKey(key) ? redisUtil.get(key) : null;
        MapDirectionDTO mapDirectionDTO = mapDirectionObject != null ? JSONUtil.toBean(mapDirectionObject.toString(), MapDirectionDTO.class) : new MapDirectionDTO() ;
        if(CollUtil.isEmpty(mapDirectionDTO.getGpsDTOList())){
            mapDirectionDTO = this.directionDriving(origins, destination);
            if (ObjectUtil.isEmpty(mapDirectionDTO)) {
                log.error("高德模拟轨迹返回数据为空, 货源号: {} - {} - {}", order.getOrderNum(), origins, destination);
            } else {
                //模拟轨迹存7天
                redisUtil.set(key, JSONObject.toJSONString(mapDirectionDTO), AMAP_GPS_API_KEY_EXPIRE);
            }
        }

        int second = 5;
        if(ObjectUtil.isNotEmpty(mapDirectionDTO) && CollUtil.isNotEmpty(mapDirectionDTO.getGpsDTOList())) {
            int abc = second / mapDirectionDTO.getGpsDTOList().size();
            for (GpsDTO mapGpsDTO : mapDirectionDTO.getGpsDTOList()) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(order.getCreateTime());
                cal.add(Calendar.SECOND, abc);//秒
                Date dates = cal.getTime();
                mapGpsDTO.setPositionTime(DateUtils.dateTimeToString(dates));
            }
        }

        return mapDirectionDTO;
    }




    public static void main(String[] args) {

        BigDecimal a =  new BigDecimal("0.1");
        System.out.println(a ==null || a.compareTo(BigDecimal.ZERO)==0 ? "a" : "b");

        HyShippingNote hyShippingNote = new HyShippingNote();
        hyShippingNote.setSendLongitude(new BigDecimal("111.1580930"));
        hyShippingNote.setSendLatitude(new BigDecimal("37.4700210"));
        hyShippingNote.setReceiveLongitude(new BigDecimal("121.5921790"));
        hyShippingNote.setReceiveLatitude(new BigDecimal("41.6914510"));

        String str = "2021-04-15 19:20:04";
        String stred = "2021-04-17 10:33:18";
        Date stardate = DateUtils.stringToDateTime(str);
        Date starendate = DateUtils.stringToDateTime(stred);

//        String mapGpsDTOS =  new AmapService().coordinate("河北省邢台市桥西区泉南西大街云锦添39号楼四层");
//        System.out.println(mapGpsDTOS);

//        List<GpsDTO>  mapGpsDTOS =  new AmapService().getMapGps(hyShippingNote);
//        System.out.println(mapGpsDTOS);
    }

    /**
     * 获取货源的模拟轨迹(用于众汇货源大厅获取里程数)
     * @param order
     * @return
     */
    public MapDirectionDTO getEstimateMileageForOrder(HyOrder order)  {
        String origins = null;
        String destination = null;
        if (order.getSendLongitude() == null
                || order.getSendLatitude() == null
                || order.getSendLongitude().compareTo(BigDecimal.ZERO) == 0
                || order.getSendLatitude().compareTo(BigDecimal.ZERO) == 0) {
            String sendresl = coordinate(order.getSendAddress());
            origins = StringUtils.isNotBlank(sendresl) ? sendresl : StringUtils.EMPTY;
        } else {
            origins = order.getSendLongitude().toString() + "," + order.getSendLatitude().toString();
        }

        if (order.getReceiveLongitude() == null
                || order.getReceiveLatitude() == null
                || order.getReceiveLongitude().compareTo(BigDecimal.ZERO) == 0
                || order.getReceiveLatitude().compareTo(BigDecimal.ZERO) == 0 ) {
            String receiveresl = this.coordinate(order.getReceiveAddress());
            destination = StringUtils.isNotBlank(receiveresl) ? receiveresl : StringUtils.EMPTY;
        } else {
            destination = order.getReceiveLongitude().toString() + "," + order.getReceiveLatitude().toString();
        }

        if (StringUtils.isBlank(origins) || StringUtils.isBlank(destination)) {
            return null;
        }

        MapDirectionDTO mapDirectionDTO = this.directionDriving(origins, destination);
        if (ObjectUtil.isEmpty(mapDirectionDTO)) {
            log.error("高德模拟轨迹返回数据为空, 货源号: {} - {} - {}", order.getOrderNum(), origins, destination);
        }

        return mapDirectionDTO;
    }
}
